<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px;">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/blog/list' }">博客管理</el-breadcrumb-item>
      <el-breadcrumb-item>发表博客</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :model="formData" ref="formData" :rules="rules" label-width="100px" label-position="right">
      <el-form-item label="标题：" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" show-word-limit maxlength="50" />
      </el-form-item>

      <el-form-item label="描述：" prop="des">
        <el-input v-model="formData.des" placeholder="请输入描述" show-word-limit maxlength="100" />
      </el-form-item>

      <el-form-item label="分类：" prop="categoryList">
        <el-select v-model="checkedCategoryId" clearable placeholder="请选择">
          <el-option
            v-for="item in categoryList"
            :key="item.categoryId"
            :label="item.name"
            :value="item.categoryId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="标签：" prop="labelIds">
        <el-select v-model="checkedLabelIds" multiple placeholder="请选择">
          <el-option
            v-for="item in labelList"
            :key="item.labelId"
            :label="item.name"
            :value="item.labelId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="主图：" prop="img" >
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadMainImg">
          <img v-if="formData.img" :src="formData.img" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="是否公开：" prop="isPublic">
        <el-radio-group v-model="formData.isPublic">
          <el-radio :label = "0">不公开</el-radio>
          <el-radio :label = "1">公开</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="内容：" prop="content" >
        <mavon-editor ref="md" v-model="formData.mdContent" @change="getMdHtml" @imgAdd="uploadContentImg" @imgDel="delContentImg" />
      </el-form-item>

    </el-form>
    <el-row type="flex" justify="center">
      <el-button type="success" plain @click="submitDraft">保存草稿</el-button>
      <el-button type="success" @click="submit('formData')">发布文章</el-button>
    </el-row>

  </div>
</template>

<script>
import blogApi from '@/api/blog';
import fileApi from '@/api/file';
import Breadcrumb from '../../components/Breadcrumb';
export default {
  components: {
    Breadcrumb
  },

  data() {
    // 自定义文章内容的校验器
    const validateContent = (rule, value, callback) => {
      if(this.formData.mdContent && this.formData.htmlContent){
        callback() //校验通过
      } else {
        callback(new Error('请输入文章内容'));
      }
    }
    return {
      formData:{
        img:'',
        des: ''
      },     // 表单数据
      labelOptions:[],
      categoryList: [],
      labelList: [],
      checkedCategoryId: '',
      checkedLabelIds: [],
      rules: {
        title:[
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        describe:[
          { required: true, message: '请输入描述', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        isPublic:[
          {required:true,message:'请输入是否公开',trigger:'change'}
        ],
        content:[
          {validator:validateContent,trigger:'change'}
        ]
      }
    };
  },

  created() {
    this.fetchCategory();
  },

  watch: {
    checkedCategoryId (newId, oldId) {
      console.log(oldId+"====>"+newId)
      this.checkedLabelIds  = [];
      if (newId) {
        this.fetchLabel(newId);
      }
    }
  },

  methods: {
    // 获取所有的分类信息
    fetchCategory() {
      blogApi.getAllCategory().then(response => {
        if (response.code === 200) {
          this.categoryList = response.data;
        }
      })
    },

    getMdHtml(mdContent,htmlContent){
      this.formData.mdContent = mdContent;
      this.formData.htmlContent = htmlContent;
    },

    // 根据分类信息的id查询标签信息
    fetchLabel(categoryId) {
      blogApi.getLabelByCategoryId(categoryId).then(response => {
        if (response.code === 200) {
          this.labelList = response.data;
        }
      })
    },

    // 上传图片 file 上传的图片对象
    uploadMainImg(file){
      const data = new FormData();
      data.append('file', file.file);
      fileApi.uploadImage(data).then(response => {
        // 将之前的图片删除
        // this.deleteImage();
        if(response.code === 200) {
          this.formData.img = response.data;
        } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有上传文件权限，请联系管理员',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    uploadContentImg(pos,file){
      const fd = new FormData();
      fd.append('file',file);
      fileApi.uploadImage(fd).then(resp => {
        if(resp.code === 200){
          this.$refs.md.$img2Url(pos, resp.data);
        }
      })
    },

    delContentImg(urlAndFileArr){
      const fileUrl = urlAndFileArr[0];//图片url
      const file = urlAndFileArr[1];//文件对象
      console.log('删除图片',fileUrl,file);
      fileApi.deleteImage(fileUrl).then(resp => {
        console.log(resp.code);
      })
    },

    // 发布文章
    submit(formName) {
      this.$refs[formName].validate( (valid) => {
        if (valid) {
          this.formData.status = 1;
          this.formData.labelIds = this.checkedLabelIds;
          blogApi.addArticle(this.formData).then(response => {
            if (response.code === 200) {
              this.$notify({
                title: '成功',
                message: '发布成功',
                type: 'success',
                duration: 1500
              });
            } else if (response.code === 306) {
              this.$notify.error({
                title: '错误',
                message: '您没有操作权限，请联系管理员',
                duration: 1500
              });
            } else {
              this.$notify.error({
                title: '错误',
                message: '系统异常，请稍后再试',
                duration: 1500
              });
            }
            this.$router.replace({path: '/blog/list'});
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },

    // 发布文章（草稿）
    submitDraft() {
      this.formData.status = 2;
      this.formData.labelIds = this.checkedLabelIds;
      blogApi.addArticle(this.formData).then(response => {
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '发布成功',
            type: 'success',
            duration: 1500
          });
          this.$router.replace({path: '/blog/list'});
        }
      })
    },


  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
